package elka.sag.logisticsystem.actor;

import java.util.ArrayList;
import java.util.List;

import elka.sag.logisticsystem.bean.*;
import org.apache.log4j.Logger;

import elka.sag.logisticsystem.bean.Order.OrderStatus;
import elka.sag.logisticsystem.message.SimpleMessage;

public class DocGeneratorActor extends BaseActor {
	private final static String RULE_PATH = "docGeneratorRules.drl";
	private final static Logger LOGGER = Logger.getLogger(DocGeneratorActor.class);
	private static final String ERROR_DOC_GENERATOR = "ERROR_DOC_GENERATOR";
	
	@Override
	public void preStart() {
		super.preStart();
		ruleService.loadRules(RULE_PATH, getClass().getName());
	}
	
	@Override
	protected void processMessage(SimpleMessage message) throws Exception {
		//dla symulacji przetwarzania czekamy przez losowy czas 0-10s
		int waitForTime = (int) (Math.random() * 2000);
		Thread.sleep(waitForTime);
		
		LOGGER.info(getClass().getSimpleName() + ": Przekazano do generowania dokumentow, orderId: " + message.getOrderId());
		Order order = repositoryService.getOrderById(message.getOrderId());
		ActionStatus actionStatus = ActionStatus.OK;
		
		List<Document> documents;
		try{
			documents = generateDocuments(order);
		} catch (Exception e) {
			//jezeli wystapil blad podczas generowania dokumentow ustaw status akcji na bledny
			actionStatus = ActionStatus.ERROR;
			documents = new ArrayList<Document>();
		}
		
		//wyznaczenie nowego statusu
		OrderStatus newOrderStatus = getNextOrderStatus(order, actionStatus);

		//aktualizacja statusu i czy_przetwarzane
        order.setStatus(newOrderStatus);
        order.setProcess(false);
		repositoryService.updateOrderStatusAndProcess(order);
		
        //zawsze nadpisujemy cala liste dokumentow
		repositoryService.setDocuments(documents, order.getId());
	}

	private List<Document> generateDocuments(Order order) throws Exception {
		List<Document> documents = new ArrayList<Document>();
		Document doc = new Document();
		doc.setName("test_doc_" + order.getId());
		doc.setText("Jakas tam tresc dokumentu dla zamowienia, orderId: " + order.getId());
		documents.add(doc);
		
		for(Article article : repositoryService.getOrderArticles(order.getId())) {
			doc = new Document();
			doc.setName("faktura");
			doc.setText("Faktura dla towaru: " + article.getName());
		}
		
		//sztuczne wytorzenie bledu
		if("Y".equals(repositoryService.getParam(ERROR_DOC_GENERATOR))) {
			LOGGER.error("Wystapil blad podczas generowania dokumentow zamowienia (nie wszystkie towary sa zarezerwowane), orderId: " + order.getId());
			throw new Exception();
		}
		
		return documents;
	}

}
